package cn.itsource.pethome.web.interceptor;

import cn.itsource.pethome.constant.Constant;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.RedisUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 *  当用户访问需要登录才能访问的资源时，检查用户是否已登录
 *      若已登录，则直接放行
 *      若未登录，就返回提示消息
 */
@Component
public class LoginIntereptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("request.getMethod()  => " + request.getMethod());
        System.out.println("request.getRequestURI()  => " + request.getRequestURI());  // /error
        //对所有OPTIONS请求直接放行
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        //从请求头中获取userToken
        String userToken = request.getHeader("userToken");
        System.out.println("userToken  => " + userToken);
        if(StringUtils.isNotBlank(userToken)){
            //以userToken为key，去Redis中获取登录用户对象的json字符串
            String loginUserJsonStr = RedisUtils.INSTANCE.get(userToken);
            System.out.println("loginUserJsonStr  => " + loginUserJsonStr);
            if(StringUtils.isNotBlank(loginUserJsonStr)){//已登录
                //请求放行之前，刷新Redis的存储数据的过期时间 重新设置为30分钟，模拟Session的超时时间
                RedisUtils.INSTANCE.set(userToken, loginUserJsonStr, Constant.EXPIRETIME_OF_LOGINUSER);
                return true;
            }
        }
        //未登录：发送响应提示消息
        response.setContentType("application/json;charset=utf-8");
        AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMsg("noUser");
        //转化为json字符串[阿里巴巴的fastjson工具包]
        String jsonString = JSON.toJSONString(ajaxResult);
        response.getWriter().write(jsonString);
        response.getWriter().flush();
        return false;
    }
}
